<template>
    <div class="operationBasicsDetail">
        <div class="header">
            <van-nav-bar title="邀约样品" left-arrow @click-left="handleLeft" v-if="!showSupplierName">
            </van-nav-bar>
        </div>
        <div class="sample" v-if="!showSupplierName">
            <div class="add_supplier-background">
                <van-form @submit="onSubmit">
                    <van-cell-group inset>
                        <van-field name="supplierName" label="供应商名称" v-model="invitationqueryParams.supplierName" is-link
                            readonly input-align="right" error-message-align="right" placeholder="请选择"
                            @click="showSupplierName = true" required
                            :rules="[{ required: true, trigger: 'onBlur', message: '请选择供应商名称' }]" />
                    </van-cell-group>
                    <van-cell-group inset>
                        <van-field name="styleName" label="商品名称" v-model="invitationqueryParams.styleName"
                            @input="(e) => { forbidRule(e, 'styleName', 'blank') }" placeholder="请输入" input-align="right"
                            error-message-align="right" required :maxlength="50" :rules="[{ required: true, trigger: 'onBlur', message: '请输入商品名称' }, {
                                validator: validatorNumbers,
                                message: '请输入正确的商品名称',
                            },]" />
                    </van-cell-group>
                    <van-cell-group inset>
                        <van-field name="productCategoryName" label="商品类目"
                            v-model="invitationqueryParams.productCategoryName" is-link readonly input-align="right"
                            error-message-align="right" placeholder="请选择" @click="show = true" required :rules="[
                                { required: true, trigger: 'onBlur', message: '请选择商品类目' },
                            ]" />
                        <van-popup v-model:show="show" round position="bottom">
                            <van-cascader v-model="cascaderValue" title="请选择商品类目" :options="options" @close="show = false"
                                @finish="onFinish" />
                        </van-popup>
                    </van-cell-group>
                    <van-cell-group inset>
                        <van-field name="brandName" label="品牌" v-model="invitationqueryParams.brandName" placeholder="请输入"
                            :maxlength="50" input-align="right" error-message-align="right" :rules="[
                                { required: false, trigger: 'onBlur', message: '请输入品牌名称' },
                                {
                                    validator: validatorNumberBrand,
                                    message: '请输入正确的品牌名称',
                                },
                            ]" />
                    </van-cell-group>
                    <van-cell-group inset>
                        <van-field name="trackingNumber" label="快递单号" v-model="invitationqueryParams.trackingNumber"
                            @input="handleTrackingNumberChange" placeholder="请输入" input-align="right"
                            error-message-align="right" required :rules="[
                                { required: true, trigger: 'onBlur', message: '请输入快递单号' },
                                {
                                    validator: validatorNumber,
                                    message: '请输入正确的快递单号',
                                },
                            ]">

                            <template #button>
                                <van-button size="small" color="#70BAFF" :loading="loading" loading-text="识别中" plain
                                    style="width: 70px;font-weight: bold;" @click="getLogisticsOcr">识别</van-button>
                            </template>

                        </van-field>
                    </van-cell-group>
                    <van-cell-group inset>
                        <van-field name="shippingCompany" label="快递公司" v-model="invitationqueryParams.shippingCompany"
                            is-link input-align="right" error-message-align="right" readonly
                            :placeholder="returnShippingCompanyColumns.length > 1 ? '请选择' : '自动识别'"
                            @click="deliveryStatusClick" required
                            :rules="[{ required: true, trigger: 'onBlur', message: '请选择快递公司' }]"></van-field>
                        <van-popup v-model:show="showReturnShippingCompany" position="bottom">
                            <van-picker :columns="returnShippingCompanyColumns" @confirm="onConfirmReturnShippingCompany"
                                @cancel="showReturnShippingCompany = false" />
                        </van-popup>
                        <div v-if="remindStatus" style="margin-left: 15px;margin-top:20px;border: none"><van-icon
                                name="warning" style="color: #FF6E00;margin-right: 10px" /><span style="color: #6F6F6F">{{
                                    remindStatusText ?
                                        '识别到多个物流/快递公司,请确认' : '未查询到物流/快递公司,请核对单号' }}</span>
                        </div>
                    </van-cell-group>

                    <div class="addtive_div-btn">
                        <van-button round block class="addtive_div" :loading="loading" loading-text="执行中..." type="primary" native-type="submit"
                            v-throttle:click>
                            保存
                        </van-button>
                    </div>
                </van-form>
            </div>
        </div>
    </div>
    <SupplierScreen :isShow="showSupplierName" @cancel="showSupplierName = false" @submit="onConfirmSupplierName">
    </SupplierScreen>
</template>
<script setup lang="ts">
import { onUnmounted, ref } from 'vue';
import { addHmProducts, getCategoryList, getDeliveryInfo } from '@/api/productList/index'
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter } from 'vue-router';
import SupplierScreen from '@/components/SupplierScreen/indexNew.vue'
const router = useRouter()
const invitationqueryParams = ref({
    supplierName: '',
    supplierId: '',
    styleName: '',
    category: '',
    brandName: '',
    shippingCompany: '',
    trackingNumber: '',
    productCategoryName: '',
    categoryId: '',
    logisticsTraceDetailList: [],
    logisticsType: ''
})
const cascaderValue = ref('')
const show = ref(false)
const options = ref()

const loading = ref(false)

const validatorNumber = (val) => /^(?![a-zA-Z]+$)[a-zA-Z0-9]{8,30}$/.test(val);
const validatorNumbers = (val) => /^[\u0020-\u007e\u4e00-\u9fa5]+$/.test(val);
const validatorNumberBrand = (val) => {
    if (val) {
        return /^[\u0020-\u007e\u4e00-\u9fa5]+$/.test(val);
    } else {
        return true
    }
}

// 定义 Column 类型
interface Column {
    text: string;
    value: string;
    logisticsTraceDetailList: any[];
    logisticsType: string;
}

const showReturnShippingCompany = ref(false)
const returnShippingCompanyColumns = ref<any>([])

const showSupplierName = ref(false)

// 输入事件、禁用规则
const forbidRule = (e: any, key: string, type: string) => {
    // 输入法表情默认不能输入
    if (type == 'emoji') {
        // emoji：输入时禁用输入法表情
        invitationqueryParams.value[key] = e.target.value.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    } else if (type == 'blank') {
        // blank：输入时禁用空格
        invitationqueryParams.value[key] = e.target.value.replace(/\s|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    }
}

/** 回退 */
const handleLeft = () => {
    router.push('/home')
}

/** 供应商名称关闭 */
const onConfirmSupplierName = (options: any) => {
    showSupplierName.value = false;
    if (options) {
        invitationqueryParams.value.supplierName = options.supplierName
        invitationqueryParams.value.supplierId = options.id;
    }
};

/** 快递公司 */
const getDiscountPrice = async () => {
    // const res = await getDicts('hm_express')
    // res.data.forEach(element => {
    //     element.text = element.dictLabel
    //     element.value = element.dictValue
    // })
    // returnShippingCompanyColumns.value = res.data
}
getDiscountPrice()
/** 快递公司关闭 */
const onConfirmReturnShippingCompany = ({ selectedOptions }) => {
    invitationqueryParams.value.shippingCompany = selectedOptions[0]?.text;
    invitationqueryParams.value.logisticsTraceDetailList = selectedOptions[0]?.logisticsTraceDetailList;
    invitationqueryParams.value.logisticsType = selectedOptions[0]?.logisticsType;
    showReturnShippingCompany.value = false;
}
/** 获取类目 */
const getOptions = async () => {
    try {
        const res = await getCategoryList();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
};
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
            if (element.children.length === 0) {
                delete element.children;
            }
        }
        return {
            text: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}
getOptions();


/** 类目最后选择 */
const onFinish = (value) => {
    show.value = false;
    invitationqueryParams.value.productCategoryName = value.selectedOptions
        .map((option) => option.text)
        .join(",");
    invitationqueryParams.value.categoryId = value.selectedOptions
        .map((option) => option.value)
        .join(",");
}
/** 保存 */
const onSubmit = async () => {
    loading.value = true
    try {
        const list = JSON.parse(JSON.stringify(invitationqueryParams.value))
        await addHmProducts(list)
        loading.value = false
        showSuccessToast({ type: 'success', message: '样品邀约成功' });
        invitationqueryParams.value = {
            supplierName: '',
            supplierId: '',
            styleName: '',
            category: '',
            brandName: '',
            shippingCompany: '',
            trackingNumber: '',
            productCategoryName: '',
            categoryId: '',
            logisticsTraceDetailList: [], // 重置为空数组
            logisticsType: '' // 重置为空字符串
        }
        // 删除app切换导致得缓存数据问题 清除
        localStorage.removeItem('invitationqueryParams')
        router.back()
    } catch (error) {
        if (error == 'timeout') {
            showFailToast('样品邀约失败');
        }
        loading.value = false
    }
}
/** app端隐藏触发保存表单 */
(window as any).saveState = function (arg) {
    if (arg.action == 'save') {
        localStorage.setItem("invitationqueryParams", JSON.stringify(invitationqueryParams.value));
    }
}
/** 离开页面、提交移除本地存储 */
onUnmounted(() => {
    invitationqueryParams.value = {
        supplierName: '',
        supplierId: '',
        styleName: '',
        category: '',
        brandName: '',
        shippingCompany: '',
        trackingNumber: '',
        productCategoryName: '',
        categoryId: '',
        logisticsTraceDetailList: [], // 重置为空数组
        logisticsType: '' // 重置为空字符串
    }
    // 删除app切换导致得缓存数据问题 清除
    localStorage.removeItem('invitationqueryParams')
})
/** app端重新打开后数据保存重新渲染 */
const rendering = () => {
    if (localStorage.getItem('invitationqueryParams')) {
        invitationqueryParams.value = JSON.parse(localStorage.getItem('invitationqueryParams') as string)
    }
}
rendering()


//提醒状态和文字
const remindStatus = ref(false)
const remindStatusText = ref(true)

//快递识别
const getLogisticsOcr = async () => {
    remindStatus.value = false
    loading.value = true
    try {
        invitationqueryParams.value.shippingCompany = ''
        invitationqueryParams.value.logisticsType = ''
        invitationqueryParams.value.logisticsTraceDetailList = []
        returnShippingCompanyColumns.value = []
        //获取快递信息如果有多条就需要选择在保存
        let deliveryInfo = {
            orderNo: invitationqueryParams.value.trackingNumber
        }
        const res = await getDeliveryInfo(deliveryInfo)
        loading.value = false
        if (res.code != 200 || res.data == null) {
            // showFailToast({ type: 'fail', message: '该订单号未查询到物流信息' });
            remindStatus.value = true
            remindStatusText.value = false
            return
        }
        //如果有多条需要人工手动选择
        if (res.data.info.length >= 2) {
            res.data.info.forEach(element => {
                let ele: Column = {
                    text: element.logisticsCompanyName || element.cpCode,  // 设置默认值
                    value: element.cpCode,  // 设置默认值
                    logisticsTraceDetailList: element.logisticsTraceDetailList || [],
                    logisticsType: element.cpCode
                };
                returnShippingCompanyColumns.value.push(ele);
                // showFailToast({ type: 'fail', message: '快递存在多条,请手动选择' });
            });
            remindStatus.value = true
            remindStatusText.value = true
        } else {
            invitationqueryParams.value.shippingCompany = res.data.info[0].logisticsCompanyName || res.data.info[0].cpCode
            invitationqueryParams.value.logisticsTraceDetailList = res.data.info[0].logisticsTraceDetailList || []
            invitationqueryParams.value.logisticsType = res.data.info[0].cpCode
        }
    } catch (error) {
        if (error == 'timeout') {
            showFailToast('识别失败');
        }
        loading.value = false
    }
}

//快递公司点击
const deliveryStatusClick = async () => {
    if (returnShippingCompanyColumns.value.length > 1) {
        showReturnShippingCompany.value = true
    }
}

//订单号发生变化清除缓存数据
const handleTrackingNumberChange = async () => {
    invitationqueryParams.value.shippingCompany = ''
    invitationqueryParams.value.logisticsType = ''
    invitationqueryParams.value.logisticsTraceDetailList = []
    remindStatus.value = false
    returnShippingCompanyColumns.value = []
}


</script>
<style lang="less" scoped>
:deep(.van-field__label) {
  width: 120px;
}
.sample {
    background-color: #f6faff;
    width: 100%;
    height: calc(100vh - 90px);
    box-sizing: border-box;
    padding: 10px 15px 94px 15px;
    margin-top: 90px;
    overflow-y: scroll;
}

:deep(.van-nav-bar__left .van-icon) {
    color: #1a1b1c !important;
}

.button {
    width: 100%;
    position: absolute;
    bottom: 20px;
}

.add_supplier-background {
    height: 100%;
    background-color: #fff;
    position: relative;
}

:deep(.van-cell-group--inset) {
    margin: 0 !important;
    border-radius: 0 !important;
}

:deep(.van-field__control) {
    color: #B8BECA !important;
}

:deep(.van-icon-arrow:before) {
    color: #B8BECA !important;
}
.operationBasicsDetail {
  width: 100%;
  // height: 100vh;
  background: #f6faff;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
  justify-content: center;
  align-content: flex-start;

  .header {
    background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
    filter: blur(0px);
    height: 90px;
    padding-top: 44px;
    box-sizing: border-box;
    width: 100%;
    position: fixed;
    z-index: 6003;

    :deep(.van-icon-arrow-left) {
      color: #1a1b1c !important;
    }

    :deep(.van-nav-bar) {
      background: none !important;
    }

    :deep(.van-nav-bar__content) {
      background-color: transparent !important;
    }
  }

}
:deep(.van-cell-group--inset) {
  margin: 0 !important;
  border-radius: 0 !important;
}

:deep(.van-form) {
  // height: 100%;
  // overflow-y: scroll;
  background-color: #fff;
  // padding-bottom: 35px !important;
}
:deep(.van-field--disabled){
  background-color: #f3f3f3;
  .van-field__control{
    color: #8492AD !important;
    -webkit-text-fill-color:#8492AD !important;
  }
  div[aria-checked=true] .van-radio__icon{
    color: #0094FF !important;
    -webkit-text-fill-color: #0094FF !important;
  }
}
.sample{
    :deep(.van-cell) {
      padding: 20px 15px;
      position: relative;
      &::after{
         content: "";
         display: block;
         height: 2px;
         width: 315px;
         background-color: #F3F3FF;
      }
  }
}

  :deep(.van-cell-group):last-child{

      .van-cell{
          border-bottom: none !important;
      }
      
  }
  :deep(.van-field__label) {
    
      color: #464E5D  !important;
  }

  :deep(.van-field__label--required){
      &::before{
          display: none;
      }
      &::after{
          color: var(--van-field-required-mark-color);
          content: "*";
      }
  }
  .imgform{
    :deep(.van-cell) {
        border-bottom: none !important;
        &::after{
            content: none;
        }
    }
  }
.addtive_div-btn {
    position: fixed;
    width: 100%;
    height: 84px;
    bottom: 0;
    left: 0;
    z-index: 110;
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    box-shadow: 0px 0px 8px 0px rgba(189,195,204,0.5);
    box-sizing: border-box;
    padding: 0 15px;
    // padding-bottom: 120px;
    .addtive_div {
        width: 320px;
        height: 44px;
        text-align: center;
        margin: auto;
        //   margin-top: 200px;
       
    }
}
</style>